#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2012 KT
#
# Author: Choonho Son <choonho.son@kt.com>
#

import subprocess
import os
import os.path
import socket
import time

from cloudcfg.lib.cmd import Cmd

__version__="1.0"

class cmd_tcp(Cmd):
	def __init__(self, logger):
		Cmd.__init__(self,logger)

	def ping(self, params):
		"""
		check ping
		
		@params (dictionary)
		ip : destination IP address
		@return : True/False
		"""
		p = params
			
		cmd = [ 'ping', p['ip'] ]
		self.run(cmd)

	def checkConnection(self, params, trial=1, interval=10):
		"""
		check TCP connection

		@params (dictionary)
		ip : destination IP address
		port : TCP port

		@return : True/False
		"""
		p = params
		HOST = p['ip']
		PORT = int(p['port'])
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		for i in range(trial):
			try:
				s.connect( (HOST, PORT) )
				s.close()
				self.logger.debug("[%d] Success to connect(%s,%s)" % (i, HOST, PORT))
				return True
			except:
				self.logger.debug("[%d] Fail to connect(%s,%s)" % (i, HOST, PORT))
				time.sleep(interval)
				continue


